package springboot.demo.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springboot.demo.annotation.NotProfile;
import springboot.demo.bean.Novel;
import springboot.demo.dao.NovelMapper;

import javax.transaction.Transactional;


@Service
@NotProfile("simple")
@Slf4j
public class TransactionInvalidServiceImpl {

    @Autowired
    NovelMapper novelMapper;

    public void innerCall(int id) {
        rollBack(id);
    }

    @Transactional
    public void rollBack(int id) {
        Novel novel = novelMapper.selectById(id);
        log.info("novel ver: {}", novel.getVer());
        novel.setVer(novel.getVer() + 1);
        novelMapper.updateById(novel);

        if (id == 1) {
            throw new RuntimeException();
        }
    }

    @Transactional
    public void rollbackForRte(int id) throws Exception {
        rollBack(id);
        throw new Exception();
    }

    @Transactional
    public void catchException(int id) {
        try {
            rollBack(id);
        } catch (RuntimeException e) {
            log.info("catch RuntimeException...");
        }
    }

    @Transactional(value = Transactional.TxType.NOT_SUPPORTED)
    public void propagationError(int id) {
        rollBack(id);
    }

    /**
     * 多数据源没有指定事务管理器
     *
     * @param id
     */
    @Transactional
    public void multiDatasource(int id) {
        rollBack(id);
    }

    /**
     * 数据库引擎不支持，既然不支持应该也不算失效？？？
     *
     * @param id
     */
    @Transactional
    public void engineNotSupport(int id) {
        rollBack(id);
    }

    /**
     * 非public、static方法不支持事务，参考事务原理
     *
     * @param id
     */
    @Transactional
    private void privateNotSupport(int id) {
        rollBack(id);
    }

}
